package com.example.excutor;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.*;

public class ExecutorDemo {

    private final static Logger logger = LoggerFactory.getLogger(ExecutorDemo.class);

    // 线程数
    private static final int threads = 5;
    // 用于计数线程是否执行完成
    static CountDownLatch countDownLatch = new CountDownLatch(threads);

    static ExecutorService executorService = Executors.newFixedThreadPool(threads);


    public static void main(String[] args) throws Throwable {
        List<Double> list = random();
        long start = System.currentTimeMillis();
        System.out.println("-------------------start-------------------");
        Double max = list.get(0);
        int maxIndex = 0;
        for (int i = 0; i < list.size(); i++) {
            if (list.get(i) >= max) {
                max = list.get(i);
                maxIndex = i;
            }
        }
        System.out.printf("---------------%d:%s------------", maxIndex, max);
        long end = System.currentTimeMillis();
        System.out.printf("-------------------耗时：%d-------------------", end - start);
    }


    public static List<Double> random() throws Throwable {
        List<Double> randoms = new ArrayList<>();
        List<Future<List<Double>>> futures = new ArrayList<>();
        for (int i = 0; i < threads; i++) {
            Future<List<Double>> future = executorService.submit(() -> {
                try {
                    List<Double> list = new ArrayList<>();
                    for (int j = 0; j < 2000000; j++) {
                        double random = Math.random() * 100;
                        list.add(random);
                    }
                    return list;
                } finally {
                    countDownLatch.countDown();
                }
            });
            futures.add(future);
        }
        countDownLatch.await();
        for (Future<List<Double>> future : futures) {
            if (future.isDone()) {
                randoms.addAll(future.get());
            }
        }
        int index = (int) (Math.random() * 100000);
        randoms.set(index, 110.56);
        System.out.printf("----------maxIndex:%d", index);
        return randoms;
    }


}
